/// <reference path="../../../../../phaser.d.ts" />

import { Groups } from "./groups"

export class PropSupply {
  // 道具 类
  constructor(scene) {
    this.scene = scene
    this._init()
  }
  supplyDelay = 2000 // 道具刷新时间
  supplyTimer = null // 道具定时器
  buffs = null // buff组
  bombs = null // 炸弹组

  // 飞机buff 配置
  _buff = {
    duration: 10 * 1000, // 持续时间 单位ms毫秒
    speed: 1, // 掉落速度
    rate: 0.2, // 掉落概率
    maxRate: 0.6, // 最大掉落概率
    increaseRate: 0.04 // 每集提升的掉落概率
  }
  // 清屏炸弹 配置
  _bomb = {
    speed: 1,
    rate: 0,
    maxRate: 0.15,
    increaseRate: 0.015
  }
  buff = {}
  bomb = {}

  _init() {
    this.buffs = new Groups(this.scene)
    this.bombs = new Groups(this.scene)
  }
  // 暂停
  pause() {
    this.scene.time.removeEvent(this.supplyTimer)
    this.buffs.children.iterate((child) => {
      child.setVelocity(0, 0)
    })
    this.bombs.children.iterate((child) => {
      child.setVelocity(0, 0)
    })
  }
  // 重置
  reset() {
    this.bombs.allkillAndHide()
    this.buffs.allkillAndHide()

    this.buff = JSON.parse(JSON.stringify(this._buff))
    this.bomb = JSON.parse(JSON.stringify(this._bomb))  

    this._productionLineRun()
  }
  // 刷新出货概率
  refresh() {
    this.bomb.rate += this.bomb.rate < this.bomb.maxRate ? this.bomb.increaseRate : 0
    this.buff.rate += this.buff.rate < this.buff.maxRate ? this.buff.increaseRate : 0
  }
  // 道具生产线 启动
  _productionLineRun() {
    this.supplyTimer = this.scene.time.addEvent({
      delay: this.supplyDelay,
      loop: true,
      callback: () => {
        if (Math.random() <= this.bomb.rate) this._createBomb()
        if (Math.random() <= this.buff.rate) this._createBuff()
      }
    })
  }

  // 生产 buff道具
  _createBuff() {
    let x = 29 + Math.ceil(Math.random() * (this.scene.gameWidth - 58))
    let y = -88
    let supply = this.buffs.get(x, y, 'prop_buff')
    supply.duration = this.buff.duration
    supply.setScale(0.8, 0.8)
    supply.setVelocity(0, this.buff.speed)
  }
  // 生产 炸弹道具
  _createBomb() {
    let x = 30 + Math.ceil(Math.random() * (this.scene.gameWidth - 60))
    let y = -107
    let supply = this.bombs.get(x, y, 'prop_bomb')
    supply.setScale(0.8, 0.8)
    supply.setVelocity(0, this.bomb.speed)
  }
  _initAnims() {

  }
  update() {
    let gameHeight = this.scene.gameHeight
    this.buffs.children.iterate((child) => {
      if (child.y - child.height / 2 > gameHeight) {
        this.buffs.killAndHide(child)
      }
    })
    this.bombs.children.iterate((child) => {
      if (child.y - child.height / 2 > gameHeight) {
        this.bombs.killAndHide(child)
      }
    })
  }
}
